import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    let message = '服务器错误';
    let errorCode = 1;

    // 打印详细错误信息以便调试
    console.error('Exception details:', exception);
    if (exception instanceof Error) {
      console.error('Error stack:', exception.stack);
    }

    // 处理HttpException
    if (exception instanceof HttpException) {
      const exceptionResponse = exception.getResponse();

      if (typeof exceptionResponse === 'object' && 'message' in exceptionResponse) {
        message = exceptionResponse['message'] as string;
      } else if (typeof exceptionResponse === 'string') {
        message = exceptionResponse;
      }
    } else if (exception instanceof Error) {
      // 处理其他Error类型
      message = exception.message;

      // 特别处理字段不存在的SQL错误，返回更友好的错误信息
      if (message.includes('Unknown column')) {
        message = '数据库字段不匹配，请检查数据库结构或更新实体定义';
      }
    }

    response.status(200).json({
      code: errorCode,
      data: null,
      msg: message
    });
  }
} 